<!--  -->
<template>
  <div class="selectLocation">
    <a-modal
      :visible="visibleSelectMapLocation"
      title="经纬度选择"
      cancelText
      :footer="null"
      width="90vw"
      :getContainer="getPopupContainer"
      @cancel="showSelectMapLocation"
    >
      <a-form layout="inline" :model="formData" ref="formMapRef">
        <a-form-item label="地址">
          <a-input
            v-model:value="formData.address"
            allowClear
            style="width: 200px"
            placeholder="请输入地址"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            ghost
            size="small"
            @click="searchAddressResult(formData.address)"
          >
            查询
          </a-button>
        </a-form-item>
        <a-form-item
          name="longitude"
          label="经度"
          :rules="[{ required: true, message: '经度值不能为空' }]"
        >
          <a-input
            style="width: 200px"
            v-model:value="formData.longitude"
            placeholder="请输入经度"
            allowClear
          />
        </a-form-item>
        <a-form-item
          label="纬度"
          name="latitude"
          :rules="[{ required: true, message: '纬度值不能为空' }]"
        >
          <a-input
            style="width: 200px"
            v-model:value="formData.latitude"
            allowClear
            placeholder="请输入纬度"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            ghost
            type="primary"
            size="small"
            html-type="submit"
            @click="
              searchLongitudeAndLatitude(formData.longitude, formData.latitude)
            "
          >
            定位
          </a-button>
        </a-form-item>
      </a-form>
      <div class="mapBorder">
        <div class="left">
          <el-amap
            :center="mapData.center"
            :zoom="mapData.zoom"
            :doubleClickZoom="mapData.doubleClickZoom"
            :jogEnable="mapData.jogEnable"
            :defaultCursor="mapData.defaultCursor"
            :animateEnable="mapData.animateEnable"
            :mapStyle="mapStyle"
            @init="initMap"
            @click="selectLocation"
          >
            <component
              v-for="mapTool in mapToolLists"
              :key="mapTool"
              :is="mapTool"
              :mapStyle="mapStyle"
            />
            <!--mark-->
            <marker-components :markerComponents="markerComponents" />
          </el-amap>
        </div>
        <div class="right">
          <div class="top">
            <template v-if="addressLists.length">
              <div
                :class="[
                  formData.index == index ? 'activeSelect' : '',
                  'mapList',
                ]"
                v-for="(item, index) in addressLists"
                :key="item"
                @click="clickLoaction(item, index)"
              >
                <div class="mapItem">
                  <div class="itemLeft">名称：</div>
                  <div class="itemRight">
                    {{ item.name || item.formatted_address || '---' }}
                  </div>
                </div>
                <div class="mapItem" v-if="item.type">
                  <div class="itemLeft">类型：</div>
                  <div class="itemRight">{{ item.type }}</div>
                </div>
                <div class="mapItem">
                  <div class="itemLeft">坐标点：</div>
                  <div class="itemRight">{{ item.location }}</div>
                </div>
                <div class="mapItem" v-if="item?.typecode">
                  <div class="itemLeft">类型编码：</div>
                  <div class="itemRight">
                    {{ item.typecode }}
                  </div>
                </div>
                <div class="mapItem" v-if="item?.pname">
                  <div class="itemLeft">详细地址：</div>
                  <div class="itemRight">
                    {{
                      item.pname + item.cityname + item.adname + item.address
                    }}
                  </div>
                </div>
              </div>
              <a-divider />
            </template>
            <template v-else>
              <a-empty description="暂无更多该附近地址信息" />
            </template>
          </div>
          <div class="confirm" @click="confirmLocation">确定</div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import markerComponents from '@/components/mapComponents/markerComponent/markerComponents.vue';
import { geocodeRegeo, searchPOI, searchDistrict } from '@/network/api/aMapApi';
import { aMapHttpRquest } from '@/network';
import { message } from 'ant-design-vue';
export default {
  props: ['visibleSelectMapLocation', 'mapStyle'],
  inject: ['getScreenFullNode'],
  components: {
    markerComponents,
  },
  data() {
    return {
      addressLists: [],
      mapData: {
        zoom: 12,
        doubleClickZoom: false,
        defaultCursor: 'pointer',
        center: [113.386974, 23.171124],
        jogEnable: false,
        animateEnable: true,
      },
      mapToolLists: [
        'el-amap-control-scale',
        'el-amap-control-control-bar',
        'el-amap-control-hawk-eye',
      ],
      map: null,
      formData: {
        address: '',
        longitude: '',
        latitude: '',
        selectValue: '',
        index: 0,
        mask: [],
      },
      markerComponents: [],
    };
  },
  computed: {
    getPopupContainer() {
      return this.getScreenFullNode();
    },
  },
  mounted() {},
  methods: {
    selectLocation(e) {
      this.searchLongitudeAndLatitude(e.lnglat.lng, e.lnglat.lat, false);
    },
    confirmLocation() {
      this.formData.longitude
        ? this.$emit('confirmLocation', this.formData)
        : message.error('请选择模型位置');
    },
    searchLongitudeAndLatitude(longitude, latitude, autoFocus = true) {
      longitude && latitude
        ? aMapHttpRquest(geocodeRegeo, {
            location: [longitude, latitude].toString(),
          }).then((res) => {
            let mark = res.regeocode.addressComponent.streetNumber?.location
              ? res.regeocode.addressComponent.streetNumber.location.split(',')
              : [longitude, latitude];
            this.formData = {
              address: res.regeocode.formatted_address,
              longitude: mark[0],
              latitude: mark[1],
              index: 0,
              selectValue: {
                address: res.regeocode.formatted_address,
                longitude: mark[0],
                latitude: mark[1],
              },
            };
            this.addressLists = [
              {
                formatted_address: res.regeocode.formatted_address,
                citycode: res.regeocode.addressComponent.citycode,
                location: mark.toString(),
              },
            ];
            autoFocus ? (this.mapData.center = mark) : '';
            this.markerComponents = [
              {
                visible: true,
                position: mark,
                angle: 0,
                title: this.formData.address,
              },
            ];
            this.searchAddressPolyline(
              res.regeocode.addressComponent.adcode
            ).then((districts) => {
              if (districts.length) {
                //区域边缘经纬度处理
                let mask = districts[0].polyline.split(';').map((item) => {
                  const local = item.split(',');
                  return [Number(local[0]), Number(local[1])];
                });
                this.formData.mask = [mask];
              } else {
                message.error('该区域暂无区域边界~');
              }
            });
          })
        : '';
    },
    //poi关键字搜索
    searchAddressResult(address) {
      address
        ? aMapHttpRquest(searchPOI, {
            keywords: address,
            extensions: 'all', //此项默认返回基本地址信息；取值为all返回地址信息、附近POI、道路以及道路交叉口信息。
          }).then((res) => {
            if (res.pois.length) {
              this.addressLists = res.pois;
              const mark = res.pois[0].location.split(',');
              this.mapData.center = mark;
              this.formData.longitude = mark[0];
              this.formData.latitude = mark[1];
              this.formData.index = 0;
              this.formData.selectValue = res.pois[0];
              this.formData.address =
                res.pois[0].pname + res.pois[0].cityname + res.pois[0].address;
              this.markerComponents = [
                {
                  visible: true,
                  position: mark,
                  angle: 0,
                  title: this.formData.address,
                },
              ];
              this.searchAddressPolyline(res.pois[0].adcode).then(
                (districts) => {
                  if (districts.length) {
                    //区域边缘经纬度处理
                    let mask = districts[0].polyline.split(';').map((item) => {
                      const local = item.split(',');
                      return [Number(local[0]), Number(local[1])];
                    });
                    this.formData.mask = [mask];
                  } else {
                    message.error('该区域暂无区域边界~');
                  }
                }
              );
            } else {
              message.warning('暂无搜索结果');
            }
          })
        : '';
    },
    /**
     * 获取区域边界
     * @param {*} keywords  行政区名称、citycode、adcode
     */
    searchAddressPolyline(keywords) {
      return new Promise((resolve, reject) => {
        aMapHttpRquest(searchDistrict, {
          keywords: keywords,
          subdistrict: 0, //是否返回下级行政区域级数
          extensions: 'all', //行政区边界坐标点 base:不返回；all:返回
        }).then((res) => {
          resolve(res.districts);
        });
      });
    },
    initMap(map) {
      this.map = map;
    },
    showSelectMapLocation() {
      this.$emit('showSelectMapLocation');
    },
    clickLoaction(val, index) {
      const mark = val.location.split(',');
      this.formData = {
        address: val.address,
        index: index,
        selectValu: val,
        longitude: mark[0],
        latitude: mark[1],
      };
      this.mapData.center = mark;
      this.markerComponents = [
        {
          visible: true,
          position: mark,
          angle: 0,
          title: val.address,
        },
      ];
    },
  },
};
</script>
<style lang="less" scoped>
::-webkit-scrollbar {
  width: 6px;
  height: 5px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #f2f2f2;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #9e9e9e;
}
.ant-empty {
  margin: 180px auto !important;
}
.mapBorder {
  display: flex;
  margin-top: 30px;
  width: 100%;
  height: 560px;
  border: 1px solid #cccccc;
  overflow: hidden;
  .left {
    flex: 4;
  }
  .right {
    flex: 1;
    width: 100%;
    height: 100%;
    .top {
      height: 520px;
      overflow: auto;
      padding: 10px;
      background-color: #f5f5f5;
      .mapList {
        background-color: white;
        padding: 5px;
        margin: 8px;
        border-radius: 10px;
        .mapItem {
          display: flex;
          .itemLeft {
            flex: 1;
            text-align: right;
          }
          .itemRight {
            flex: 2;
          }
        }
      }
      .mapList:hover {
        cursor: pointer;
      }
    }
    .confirm {
      background-color: #3e8ef7;
      text-align: center;
      height: 40px;
      color: white;
      line-height: 40px;
    }
    .confirm:hover {
      cursor: pointer;
    }
  }
}
.activeSelect {
  border: 1px solid #0cf;
}
</style>
